const Koa = require('koa')
const app = new Koa()
const fs = require('fs');
const url = require('url');
const path = require('path')

app.use(require('koa-static')(__dirname + '/public'))

app.use(async (ctx, next) => {
  var requestUrl = ctx.url;
  console.log(requestUrl, 'requestUrl')
  var pathName = url.parse(requestUrl).pathname;

  //对路径解码，防止中文乱码
  var pathName = decodeURI(pathName);
  var filePath = path.resolve(__dirname + pathName);

  fs.stat(filePath, (err, stats) => {
    console.log(stats.isDirectory(), 'status----')
    //如果路径是目录
    if (!err && stats.isDirectory()) {
      var html = "<head><meta charset = 'utf-8'/></head><body><ul>";
      //读取该路径下文件
      fs.readdir(filePath, (err, files) => {
        if (err) {
          console.log("读取路径失败！");
        } else {
          //做成一个链接表，方便用户访问
          var flag = false;
          for (var file of files) {
            //如果在目录下找到index.html，直接读取这个文件
            if (file === "index.html") {
              readFile(filePath + (filePath[filePath.length - 1] == '/' ? '' : '/') + 'index.html', "text/html");
              flag = true;
              break;
            };
            html += `<li><a href='${file}'>${file}</a></li>`;
          }
          if (!flag) {
            html += '</ul></body>';
            // response.writeHead(200, { "content-type": "text/html" });
            // response.end(html);
            ctx.body = html;
          }
        }
      });
    }

    //读取文件的函数
    function readFile(filePath, contentType) {
      ctx.type = `content-type: ${contentType}`
      // response.writeHead(200, { "content-type": contentType });
      //建立流对象，读文件
      var stream = fs.createReadStream(filePath);
      //错误处理
      stream.on('error', function () {
        ctx.type = `content-type: ${contentType}`
        ctx.status = '404';
        // response.writeHead(500, { "content-type": contentType });
        // response.end("<h1>500 Server Error</h1>");
        ctx.body = `<h1>500 Server Error</h1>`
      });
      //读取文件
      stream.pipe(response);
    }
  });
})


app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})


app.listen(9898, () => console.log(9898))